<?php
// 会员消息表

namespace app\console\model;

use think\Model;
use think\Request;

class MemberMessage extends Model
{

    protected $resultSetType = 'collection';
   protected $table = 'sun_message';
    // 消息类型获取器
    public function getTypeTextAttr($data, $value)
    {
        //$types = ['1' => '系统消息', '2' => '订单消息','3' => '会员消息'];

       // return $types[$value['type']];
    }


    // 模型事件
    protected static function init()
    {
        self::event('before_write', function ($data) {
            $d = implode(',',$data->member_id);

            if($data['message_type'] == 3){

                $data->member_id = implode(',',$data->member_id);
            }
            $data->create_time = date('Y-m-d H:i:s', time());

        });
        // 写入之前
        self::event('after_insert', function ($data) {

            if($data['message_type'] == 3){
                $insertAll = [];

                $member = explode(',',$data->member_id);
                foreach ($member as $k => $v){
                    $insertAll[] = [
                        'member_id' => $v,
                        'title' => $data['title'],
                        'content' => $data['content'],
                        'create_time' => $data['create_time'],
                        'message_id' => $data['id']
                    ];
                    //
                    $content = strip_tags(str_replace('&nbsp;','',$data['content']));
                    (new \app\index\controller\MemberMessage())->jpushMessage($v,$data['title'],$content,1);
                }
                (new \app\index\model\MemberMessage())->insertAll($insertAll);

            }
            $data->create_time = date('Y-m-d H:i:s', time());

        });
        // 写入之前
        self::event('before_delete', function ($data) {
           // db('mem_mess')->where(['message_id' => $data->id])->delete();

        });
    }
}
